<?php
class Scanpay extends BZ_Controller
{
    public function _init()
    {
        $this->load->driver('cache');
        $this->load->helper(array('validation', 'api', 'common'));
        $this->load->library('alipay/authorization', null, 'authorization');
        $this->load->model('scenery_base_model', 'scenery_base');
        $this->load->model('goods_base_model', 'goods_base');
        $this->load->model('scenery_reviews_model', 'scenery_reviews');
        $this->load->model('order_base_model', 'order_base');
        $this->load->model('pay_record_model', 'pay_record');
        $this->load->model('order_profit_model', 'order_profit');
        $this->load->model('order_source_model', 'order_source');
        $this->load->model('make_code_model', 'make_code');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('getpwd_phone_model', 'getpwd_phone');
        $this->load->model('goods_map_profit_model', 'goods_map_profit');
        $this->load->model('user_model', 'user');
        $this->load->model('tourism_goods_base_model', 'tourism_goods_base');
        $this->load->model('bind_user_model', 'bind_user');
        $this->load->model('scan_recommend_products_model', 'scan_recommend_products');
        $this->load->model('region_model', 'region');
    }

    /**
     * 景区详情页
     */
    public function index($sid)
    {
        $result = $this->scenery_base->findById($sid);
        if ($result->num_rows() <= 0) { //景区不存在
            show_404();
        }

        //用cookie 保存2小时的景区编号 用于区分是扫描购进来的还是 普通过来的
        set_cookie('scan_sid',$sid,7200);

        $openUser = json_decode(get_cookie('bzopen'), TRUE);
        if (empty($openUser['openid']) && empty($openUser['ali_user_id'])) {
            if (validateWeiXin()) {
                $openUser = $this->weChat($sid);
            } else if(validateAliapp()) {
                $openUser = $this->aliAuth($sid);
            }
        }

        if (!empty($openUser['openid']) || !empty($openUser['ali_user_id'])) {
            $bindUser = $this->bind_user->find($openUser);
            if ($bindUser->num_rows() > 0) {
                $user = $this->user->findById($bindUser->row()->uid);
                if ($user->num_rows() > 0) {
                    $error = $this->_login($user->row());  //微信过来  直接登录
                    if ($error) {
                        $this->alertError($error);
                    }
                }
            } else {
                $this->createUser($openUser);
            }
        }

        $sceneryBase = $result->row();
        $data['sceneryBase'] = $sceneryBase;
        $data['headTitle'] = $sceneryBase->name_hanzi;

        $result1 = $this->goods_base->findByUidParams(array('uid'=>$sceneryBase->uid, 'is_scan' => 2, 'orderby'=>'cat_id ASC, goods_id ASC'));
        $goodsBase = array();
        foreach ($result1->result() as $item) {
            $goodsBase[$item->cat_id][] = $item;
        }
        $data['goodsBase'] = $goodsBase;
        $data['cat_id'] = array(1=>'普通票', 2=>'联票', 8=>'年票', 16=>'团队票');

        $this->load->view('scenic/scanpay/index', $data);
    }

    /**
     * 微信授权
     */
    protected function weChat($sid)
    {
        include_once(getcwd()."/application/libraries/wxpay/WxPayPubHelper/WxPayPubHelper.php");
        $jsapi = new JsApi_pub();
        if (!isset($_GET['code'])) {
            $return_url = urlencode(site_url('scenic/scanpay/index/'.$sid));
            $url = $jsapi->createOauthUrlForCode($return_url);
            header("Location:$url");
        }
        
        $jsapi->setCode($_GET['code']);
        $result = $jsapi->curl($jsapi->createOauthUrlForOpenid());
        $urlOne = "https://api.weixin.qq.com/sns/userinfo?access_token=".$result->access_token."&openid=".$result->openid."&lang=zh_CN";
        $userInfo = $jsapi->curl($urlOne);
        $openUser = array('openid' => $userInfo->openid, 'personal_photo' => $userInfo->headimgurl, 'alias_name' => filterEmoji($userInfo->nickname));
        set_cookie('bzopen', json_encode($openUser), 7200);
        return $openUser;
    }

    /**
     * 支付宝授权
     */
    protected function aliAuth($sid)
    {
        $authCode = $this->input->get('auth_code');
        if (empty($authCode)) {
            $return_url = site_url('scenic/scanpay/index/'.$sid);
            $appid = $this->authorization->getAppid();
            $url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.$appid .'&scope=auth_userinfo&redirect_uri='. $return_url;
            header("Location:$url");
        }
        $params = $this->authorization->getAutoParams();
        $params['method'] = 'alipay.system.oauth.token';
        $params['code'] = $authCode;
        $params['sign'] = $this->authorization->generateSign($params, 'RSA');
        $alipayTokenResponse = json_decode($this->authorization->curl($params));
        $access_token = $alipayTokenResponse->alipay_system_oauth_token_response->access_token;

        return $this->getAlipayUserInfor($access_token);
    }

    private function  getAlipayUserInfor($auth_token)
    {
        $paramsUserInfor = $this->authorization->getAutoParams();
        $paramsUserInfor['method'] = 'alipay.user.userinfo.share';
        $paramsUserInfor['auth_token'] = $auth_token;
        $paramsUserInfor['sign'] = $this->authorization->generateSign($paramsUserInfor, 'RSA');
        $result = json_decode($this->authorization->curl($paramsUserInfor));
        $alipayUserInfor = $result->alipay_user_userinfo_share_response;
        $openUser = array(
            'ali_user_id' => $alipayUserInfor->alipay_user_id,
            'personal_photo' => $alipayUserInfor->avatar,
            'alias_name' => empty($alipayUserInfor->nick_name) ? '着想会员' : filterEmoji($alipayUserInfor->nick_name)
        );
        set_cookie('bzopen', json_encode($openUser), 7200);
        return $openUser;
    }

    /**
     * 扫码预订页面
     */
    public function booking()
    {
        $data['mobile'] = ''; //取得上一次填写的手机号码
        $data['sfz'] = ''; //取得上一次填写的身份证
        if ($this->uid) {
            $result = $this->order_base->findByRecently(array('payer_uid'=>$this->uid), 'phone, sfz');
            if ($result->num_rows() > 0) {
                $data['mobile'] = $result->row(0)->phone;
                $data['sfz'] = $result->row(0)->sfz;
            }
        }
        $this->load->view('scenic/scanpay/booking', $data);
    }

    /**
     * 确认订单门票
     */
    public function orderTicket()
    {
        $scenicId = $this->input->post('scenicId');
        $ticketId = $this->input->post('ticketId');
        $result = $this->scenery_base->findBySid($scenicId);
        if ($result->num_rows() <= 0) {//景区不存在，则跳转到首页
            echo json_encode(array(
                'status' => false,
                'messages' => $this->config->www_base_url
            ));exit;
        }
        $result2 = $this->goods_base->findByGoodsId($ticketId);
        if ($result2->num_rows() <= 0) { //如果为查询到当前门票则弹框选择其它门票
            echo json_encode(array(
                'status' => false,
                'messages' => false
            ));exit;
        }
        $data['tickets'] = $result2->result();

        echo json_encode(array(
            'status'   => true,
            'messages' => $this->load->view('scenic/scanpay/orderTicket', $data, true)
        ));exit;
    }
    
    /**
     * 弹框
     */
    public function ticketPop()
    {
        $scenicId = $this->input->post('scenicId');
        $ticketId = $this->input->post('ticketId');
        $buyticket = $this->input->post('buyticket');
        $result = $this->scenery_base->findBySid($scenicId);
        if ($result->num_rows() > 0) {
            $sceneryBase = $result->row(0);
            $result1 = $this->goods_base->findByUidParams(array('uid'=>$sceneryBase->uid, 'is_scan' => 2, 'orderby'=>'cat_id ASC, goods_id ASC'));
            $goodsBase = array();
            foreach ($result1->result() as $item) {
                $goodsBase[$item->cat_id][] = $item;
            }
            $data['goodsBase'] = $goodsBase;
        } else {
            $data['goodsBase'] = array();
        }
        $data['goods_id'] = $buyticket ? array_keys($buyticket) : array();
        $data['cat_id'] = array(1=>'普通票', 2=>'联票' ,8=>'年票', 16=>'团队票');
        $data['cat_icon'] = array(1=>'&#xe615;', 2=>'&#xe617;', 8=>'&#xe616;', 16=>'&#xe619;');

        echo $this->load->view('scenic/scanpay/ticketPop', $data, true);
        exit;
    }
    
    /**
     * 计算总金额
     */
    public function orderTotal()
    {
        $ticketId = $this->input->post('ticketId');//页面首次加载
        $buyticket = $this->input->post('buyticket');
        if (!empty($buyticket)) {
            $goodsIds = array_keys($buyticket);
        } else {
            $goodsIds = array($ticketId);
        }
        $result = $this->goods_base->orderTotal(array('goods_ids'=>$goodsIds));
        if ($result->num_rows() <= 0) {
            echo json_encode(array(
                'status' => false,
                'messages' => $this->config->wap_base_url.'scenic/home/index.html'
            ));exit;
        }

        $orderTotal = 0;
        $orderBouns = 0;
        $ticketTotal = array();
        $required_sfz = 0; //身份证是否必填。
        foreach ($result->result() as $item) {
            $byNum = isset($buyticket[$item->goods_id]['buy_num']) ? $buyticket[$item->goods_id]['buy_num'] : 1;
            $ticketTotal[$item->goods_id] = bcmul($item->market_price, $byNum, 2);
            $orderTotal = bcadd($orderTotal, $ticketTotal[$item->goods_id], 2);
            if ($item->sfz_required == 1) {
                $required_sfz = 1;
            }
        }

        echo json_encode(array(
            'status'      => true,
            'ticketTotal' => $ticketTotal,
            'orderTotal'  => $orderTotal,
            'required_sfz'=> $required_sfz
        ));exit;
    }

    /**
     * 附近热门景区
     */
    public function scenicNearby()
    {
        $sid = $this->input->get('sid');

        $data = array();
        
        $cityid = $this->input->get('cityid');
        $provinceid = $this->input->get('provinceid');
        $flag = $this->input->get('flag', true);
        $url = $flag ? 'scenic/scanpay/scenicNearby' : 'scenic/payment/ajaxScenic';

        $productId = $this->getProductId(array('sid' =>$sid, 'type' => 1));

        $result = '';
        if ($productId) {
            $result = $this->scenery_base->sceneryHotTickets(array('sid' => $productId, 'not_sid' => $sid, 'limit' => 4)); //按推荐景区来
        }

        if ( !$result) {
            $params = array('not_sid' => $sid, 'city_id' => $cityid, 'limit' => 4);
            $sceneryList = $this->scenery_base->sceneryHotTickets($params); //按市统计
            $scenicNearby = array();
            if ($sceneryList->num_rows() == 0) {
                unset($params['city_id']);
                $params['province_id'] = $provinceid;
                $sceneryList = $this->scenery_base->sceneryHotTickets($params); //按省统计
                if ($sceneryList->num_rows() == 0) {
                    unset($params['province_id']);
                    $sceneryList = $this->scenery_base->sceneryHotTickets($params); //销售统计
                    if ($sceneryList->num_rows() > 0) {
                        $scenicNearby = $sceneryList->result();
                    }
                } else {
                    $scenicNearby = $sceneryList->result();
                }
            } else {
                $scenicNearby = $sceneryList->result();
            }
        } else {
            $scenicNearby = $result->result();
        }

        $data = array();
        if ( ! empty($scenicNearby)) {
            $data['sceneryList'] = $scenicNearby;
        }
        $data['cityName'] = $this->getCityName($cityid);
        echo json_encode(
                array(
                    'html' => $this->load->view($url, $data, true),
                    
                )
            );
        exit;
    }

    private function getProductId($params)
    {
        $result = $this->scan_recommend_products->findProductsId($params);
        if ($result->num_rows() == 0) {
            return '';
        }

        $productId = $result->row()->products_id;
        if ($productId) {
            return explode(',', rtrim($productId, ','));
        } else {
            return '';
        }
    }

    private function getCityName($regionId)
    {
        $result = $this->region->findById($regionId);

        if ($result->num_rows() > 0) {
            return $result->row()->region_name;
        }
        return '';
    }

    /**
     * 周边特产
     */
    public function tourismNearby()
    {
        $sid = $this->input->get('sid');
        $cityid = $this->input->get('cityid');
        $provinceid = $this->input->get('provinceid');
        $flag = $this->input->get('flag');
        $url = $flag ? 'scenic/scanpay/tourismNearby' : 'scenic/payment/ajaxTourism';

        $productId = $this->getProductId(array('sid' =>$sid, 'type' => 3)); //商品

        $result = '';
        if ($productId) {
            $result = $this->tourism_goods_base->findBzCurrencyTourism(array('goods_sn' => $productId, 'limit' => 4)); //按推荐景区来
        }
        if ( !$result) {
            $params = array('city_id' => $cityid, 'goods_native' => 2, 'sort' => 3, 'limit' => 4);
            $tourismList = $this->tourism_goods_base->findBzCurrencyTourism($params); //按市统计
            $tourismNearby = array();
            if ($tourismList->num_rows() == 0) {
                unset($params['city_id']);
                $params['province_id'] = $provinceid;
                $tourismList = $this->tourism_goods_base->findBzCurrencyTourism($params); //按省统计
                if ($tourismList->num_rows() == 0) {
                    unset($params['province_id']);
                    $tourismList = $this->tourism_goods_base->findBzCurrencyTourism($params); //销售统计
                    if ($tourismList->num_rows() > 0) {
                        $tourismNearby = $tourismList->result();
                    }
                } else {
                    $tourismNearby = $tourismList->result();
                }
            } else {
                $tourismNearby = $tourismList->result();
            }
        } else {
            $tourismNearby = $result->result();
        }

        $data = array();
        if ( ! empty($tourismNearby)) {
            $data['tourismList'] = $tourismNearby;
        }
        $data['cityName'] = $this->getCityName($cityid);
        echo json_encode(
                array(
                    'html' => $this->load->view($url, $data, true)
                )
            );
        exit;
    }

    /**
     * 周边酒店
     */
    public function hotelNearby()
    {
        $sid = $this->input->get('sid');
        $cityid = $this->input->get('cityid');
        $provinceid = $this->input->get('provinceid');
        $flag = $this->input->get('flag');
        $url = $flag ? 'scenic/scanpay/hotelNearby' : 'scenic/payment/ajaxHotel';

        $productId = $this->getProductId(array('sid' =>$sid, 'type' => 2)); //酒店
        $sql = $productId;
        if ($productId) {
            $apiUrl = $this->config->hotel_api_url. 'admin/OrderCenter/HotelGrid';
            $res = getApiDynamic(array('hotel_id' => json_encode($productId), 'size' => 4), $apiUrl);
            $result = json_decode($res);
            $sql = $result;
            if ($result->status === 0) {
                $hotelNearby = $result->data->list;
            }
        } else {
            $apiUrl = $this->config->hotel_api_url. 'm/hotel/GetAroundHotel';
            $res = getApiDynamic(array('city_id' => $cityid, 'province_id' => $provinceid, 'limit' => 4), $apiUrl);
            $result = json_decode($res);
            if ($result->status === 0) {
                $hotelNearby = $result->data;
            }
        }

        $data = array();
        if ( ! empty($hotelNearby)) {
            $data['hotelList'] = $hotelNearby;
        }
        echo json_encode(
                array(
                    'html' => $this->load->view($url, $data, true),
                    // 'sql'  => $sql
                )
            );
        exit;
    }

    /**
     * 自助导游城市一站通
     */
    public function zzdyCities()
    {
        $cityid = $this->input->get('cityid');
        $data['result'] = json_decode(apiCurl($this->config->zzdy_url. 'api/api/findTourismBanner', array('city_id' => $cityid)));
        echo json_encode(
                array(
                    'html' => $this->load->view('scenic/scanpay/zzdyCity', $data, true)
                )
            );
        exit;
    }

    /**
     * 周边餐饮
     */
    public function restaurantNearby()
    {
        $sid = $this->input->get('sid');
        // $cityid = $this->input->get('cityid');
        // $flag = $this->input->get('flag', true);
        // $url = $flag ? 'scenic/scanpay/restaurantNearby' : 'scenic/payment/ajaxScenic';
        $url = 'scenic/scanpay/restaurantNearby';
        $productId = $this->getProductId(array('sid' =>$sid, 'type' => 4)); //餐饮

        $data = array();
        $status = false;
        if ($productId) {
            $result = $this->scenery_base->sceneryHotTickets(array('sid' => $productId, 'not_sid' => $sid, 'limit' => 4)); //按推荐景区来
            if ($result->num_rows() > 0) {
                $data['restaurantList'] = $result->result();
                $status = true;
            }

            
        } else {
            // $params = array('not_sid' => $sid, 'city_id' => $cityid, 'limit' => 4);
            // $result = $this->scenery_base->sceneryHotTickets($params); //按市统计
        }

        echo json_encode(
                array(
                    'html' => $this->load->view($url, $data, true),
                    'status' => $status
                )
            );
        exit;
    }

    /**
     * 获取门票描述信息
     */
    public function ticketDescript()
    {
        $ticketId = $this->input->post('goods_id', TRUE);
        $result = $this->goods_base->findByGoodsId($ticketId);
        $data['ticket'] = $result->row(0);
        echo $this->load->view('scenic/scanpay/ticketDescript', $data, true);
        exit;
    }

    /**
     * 获取门票描述信息
     */
    public function buyTicket()
    {
        $ticketId = $this->input->post('goods_id', TRUE);
        $result = $this->goods_base->findByGoodsId($ticketId);
        $data['ticket'] = $result->row(0);
        echo $this->load->view('scenic/scanpay/buyTicket', $data, true);
        exit;
    }

    /**
     * 景区详情
     */
    public function scenicInfo($sid)
    {
        if (empty($sid) || $sid < 0) {
            $this->jsonMessage('景区不存在');
        }
        $result = $this->scenery_base->findById($sid);
        
        if ($result->num_rows() == 0) {
            $this->jsonMessage('景区不存在');
        }
        $this->jsonMessage('', $result->row()->info);
    }

    private function checkUser($mobilePhone)
    {
        $result = $this->user->validateMobilePhone($mobilePhone);
        if ($result->num_rows() == 0) {
            $postData = array(
                'user_name' => $mobilePhone,
                'mobile_phone' => $mobilePhone,
            );
            return $this->createUser($postData);
        }else {
            $result = $result->row();
            if ($error = $this->_login($result)) {
                return $error;
            }
        }
    }

    /**
     * 如果用户没有账号就让他注册 并登陆
     */
    private function createUser($userInfo)
    {
        $this->db->trans_begin(); //开启事务  开始插入数据
        $parentName = get_cookie('true_user');
        $parent_id = UTID_BEIZHU;
        $amount_bonus = 0;

        $sid = get_cookie('scan_sid');

        if ($sid == 1481){
            $amount_bonus = 100;
        }
        if (!empty($parentName)) {
            $parent = $this->user->validateName($parentName);
            if ($parent->num_rows() > 0) {
                $parent_id = $parent->row()->uid;
                // if (in_array($parent_id, array(2002745, 3519856))) { //蛇蟠岛的就送游币
                //     $amount_bonus = 100;
                // }
            }
        }

        $postData = array(
            'user_name' => isset($userInfo['user_name']) ? $userInfo['user_name'] : '',
            'mobile_phone' => isset($userInfo['mobile_phone']) ? $userInfo['mobile_phone'] : '',
            'personal_photo' => isset($userInfo['personal_photo']) ? $userInfo['personal_photo'] : '',
            'alias_name' => isset($userInfo['alias_name']) ? $userInfo['alias_name'] : ''
        );
        $userId = $this->user->insertUser($postData, $parent_id);
        $userAccountId = $this->user_account->insertUserAccount($userId, $amount_bonus);
        if (validateWeiXin()) {
            $this->bind_user->insertBindUser(array('uid' => $userId, 'openid' =>$userInfo['openid']));
        } elseif (validateAliapp()) {
            $this->bind_user->insertBindUser(array('uid' => $userId, 'ali_user_id' =>$userInfo['ali_user_id']));
        }

        if ($this->db->trans_status() === FALSE || !$userId || !$userAccountId) {
            $this->db->trans_rollback();
             return '用户购买失败';
        } else {
            $this->db->trans_commit();
            // 注册成功了 准备登陆
            $userType = $this->usertype(UTID_CUSTOMER);
            $session = array(
                'ACT_UID'        => $userId,
                'ACT_UTID'       => UTID_CUSTOMER,
                'ACT_TYPENAME'   => urlencode($userType['type_zh']),
                'ACT_TYPE'       => $userType['type_en'],
                'ACT_EXTRA'      => 0,
                'ALIAS_NAME'     => $postData['alias_name'],
                'OWNER_ID'       => $userId,
                'OWNER_NAME'     => $postData['user_name'],
                'PARENT_ID'      => 16,
                'PERSONAL_PHOTO' => $postData['personal_photo']
            );
            set_cookie('frontUser', serialize($session), 43250);
            $this->_setLogin($session); //设置登录信息
        }
    }

    /**
     * 用户登陆
     */
    private function _login($user)
    {
        if ($user->user_type & UTID_PROVIDER) {
            return '供应商账号不可购买哦';
        }

        if ($user->flag == 2) {
            return '此帐号已被冻结，请与管理员联系';
        }
        $userType = $this->usertype($user->user_type);
        $session = array(
            'ACT_UID'        => $user->uid,
            'ACT_UTID'       => $user->user_type,
            'ACT_TYPENAME'   => urlencode($userType['type_zh']),
            'ACT_TYPE'       => $userType['type_en'],
            'ACT_EXTRA'      => $user->extra,
            'ALIAS_NAME'     => urlencode($user->alias_name),
            'OWNER_ID'       => $user->uid,
            'OWNER_NAME'     => $user->user_name,
            'PARENT_ID'      => $user->parent_id,
            'PERSONAL_PHOTO' => urlencode($user->personal_photo),
        );
        set_cookie('frontUser', serialize($session), 43250);
        $this->_setLogin($session);
        return false;
    }

    /**
     * 设置登录信息
     */
    private function _setLogin($session)
    {
        $this->uid = $session['ACT_UID']; //获取session uid
        $this->userType = $session['ACT_UTID']; //获取用户类型
        $this->userName = $session['OWNER_NAME']; //获取用户名
        $this->aliasName = urldecode($session['ALIAS_NAME']); //获取用户别名
        $this->userTypeEn = $session['ACT_TYPE']; //获取英文名
        $this->userTypeName = urldecode($session['ACT_TYPENAME']); //获取用户别名
        $this->userParentId = $session['PARENT_ID']; //获取上级用户编号
        $this->personalPhoto = '';
    }

    /**
     * 景区
     * 提交，生成订单
     * 
     */
    public function scanpaySubmit()
    {
        $visitorTel = $this->input->post('visitor_telephone', TRUE);
        if (!validateMobilePhone($visitorTel)) {
            $this->jsonMessage('手机号码格式不正确');
        }
        
        if (empty($this->uid)) { //没有登陆
            $captcha = $this->input->post('captcha');
            if (strlen($captcha) != 6) { //没有登陆需要验证短信验证码
                $this->jsonMessage('请输入6位的短信验证码');
            }

            $getpwdPhone = $this->getpwd_phone->validateCaptcha($visitorTel, $captcha);
            if ($getpwdPhone->num_rows() == 0) {
                $this->jsonMessage('短信验证码不正确');
            }
            $error =$this->checkUser($visitorTel);
            if ($error) {
                $this->jsonMessage($error);
            }
        }

        $visitorName = '扫码游客';
        $visitorSfz = $this->input->post('visitor_sfz') ? strtoupper($this->input->post('visitor_sfz', TRUE)) : 0;
        $requiredSfz = $this->input->post('required_sfz');
        if ($requiredSfz && !$visitorSfz) {
            $this->jsonMessage('请填写身份证号码');
        }
        if ($visitorSfz && !validateSfz($visitorSfz)) {
            $this->jsonMessage('身份证格式不正确');
        }

        $buyticket = $this->input->post('buyticket');
        $goodsIds = $buyticket ? array_keys($buyticket) : array();
        //获取所有门票
        $result = $this->goods_base->findByParams(array('goods_ids'=>$goodsIds));
        if ($result->num_rows() <= 0) {
            $this->jsonMessage('门票信息有误');
        }

        $tickets = $result->result();
        //来源修改
        $payerNames = array();
        $result2 = $this->order_source->findByParams(array('goods_ids'=>$goodsIds));
        if ($result2->num_rows() > 0) {
            foreach ($result2->result() as $source) {
                if ($source->uid == 0) {
                    $payerNames[$source->goods_id] = $source->source;
                } else {
                    if ($this->uid == $source->uid) {
                        $payerNames[$source->uid][$source->goods_id] = $source->source;
                    }
                }
            }
        }

        $resutlScenery = $this->scenery_base->findBySid($tickets[0]->sid);
        if ($resutlScenery->num_rows() == 0) {
            $this->jsonMessage('景区不存在');
        }

        $resutlScenery = $resutlScenery->row();


        $this->db->trans_begin();

        if (!$visitorSfz) { //如果未填写身份证，则发送验证码
            /*
            if (strtolower($captcha) != strtolower(get_cookie('captcha'))) {
                $this->jsonMessage('验证码输入有误！');
            }*/

            $lastCode = $this->make_code->findByLastId();
            $visitorSfz = intval($lastCode->row(0)->code)+1;
            $insertLast = $this->make_code->insertMakeCode($visitorSfz);
        }

        $payRecordId = $this->createPayRecode(); //生成pay_record记录

        $orderBase = array(); //订单表数据
        $scenicProfit = array(); //订单分润表数据

        //更新pay_record表的信息
        $level      = 0;
        $cat_ids    = array();
        $goods_ids  = array();
        $goods_nums = array();
        $order_ids  = array();
        $orderBouns = 0; //订单金币应该支付总数
        $orderPayTotal = 0;  //订单实际应该支付的总价
        $payRecordBody = ''; //订单门票购买信息

        foreach ($tickets as $key=>$ticket) {
            $goodsId = $ticket->goods_id;
            $buyDate = date('Y-m-d'); //当前购买日期
            $buyNum  = $buyticket[$ticket->goods_id]['buy_num'];  //当前购买数量
            $error = $this->validateBuyTicket($ticket, $buyNum);
            if (!empty($error)) {
                $this->db->trans_rollback();
                $this->jsonMessage($error);
            }


            //预订延后起 + 提前预定天数可以使用
            $startTime = time();

            //使用有效期 - 多少天后失效
            $endTime = 0; //结束时间
            if (in_array($ticket->cat_id, array(8))) { //如果是年票 8:年票
                $endTime = strtotime(date('Y-12-31 23:59:59'));
            } else if ($ticket->validity_days > 0) {
                $startvalid = $startTime ? $startTime : time();
                $endTime = $startvalid+$ticket->validity_days*24*60*60;
            }

            if (strlen($endTime) > 11) {
                $this->db->trans_rollback();
                $this->jsonMessage('有效期结束时间有误');
            }

            $shop_price = $ticket->market_price; //着想销售价
            $ticketPayTotal = bcmul($shop_price, $buyNum, 2); //当前门票需支付总价

            $orderBase['cat_id'] = $ticket->cat_id;
            $orderBase['goods_id'] = $ticket->goods_id;
            $orderBase['goods_num'] = $buyNum;
            $orderBase['payer_uid'] = $this->uid;
            $orderBase['payer_name'] = (isset($payerNames[$this->uid][$goodsId]) ? $payerNames[$this->uid][$goodsId] : (isset($payerNames[$goodsId]) ? $payerNames[$goodsId] : ($this->aliasName ? $this->aliasName : $this->userName)));
            $orderBase['bit_use'] = 0;
            $orderBase['bit_pay'] = 0; //$trade_way=4是它网过来的订单，默认是0，以支付值是65536
            //$orderBase['bit_ref'] = 0; 暂不清楚
            $orderBase['bit_opt'] = $ticket->bit_opt;
            //1官网交易 -4它网支付交易 -8景区到付 -16在线支付 -64着想或别网门票 -128议价自主结算 -258议价系统结算 -512总代结（用于统计）-2048淘宝交易 -4096去哪儿 -8192百度直达号 -16384美团交易
            $orderBase['bit_wan'] = 1|16|64;
            $orderBase['goods_name'] = $ticket->goods_name;
            $orderBase['provider_name'] = $ticket->provider_name;
            $orderBase['add_rank'] = $ticket->add_rank*$buyNum;
            $orderBase['play_name'] = $visitorName;
            $orderBase['sfz'] = $visitorSfz;
            $orderBase['phone'] = $visitorTel;

            $orderBase['price'] = $shop_price;
            $orderBase['number'] = $buyNum;
            $orderBase['amount_total'] = $ticketPayTotal;
            $orderBase['amount_bouns'] = 0;
            $orderBase['amount_fee'] = $ticketPayTotal;
            $orderBase['amount_provide'] = $shop_price; //bcmul($provide_price, $buyNum, 2);
            $orderBase['amount_second_provide'] = 0;

            $orderBase['pay_method'] = 0; //支付方式
            $orderBase['ordertime'] = time();
            $orderBase['paytime'] = 0;
            $orderBase['plantime'] = strtotime($buyDate);
            $orderBase['usetime'] = 0;
            $orderBase['start_time'] = $startTime;
            $orderBase['end_time'] = $endTime;
            $orderBase['mac_ids'] = $ticket->mac_ids;
            $orderBase['other_id'] = 0; //它网对接着想
            $orderBase['out_other_id'] = 0; //着想对接它网
            //$orderBase['out_other_id_is_new'] = 0; //他网单号是否是新接口对接的-着想对接他网 0-不是 1-是
            //$orderBase['api_is_new_or_old'] = 'odd'; //他网对接着想的接口是新接口还是老接口
            $orderBase['sid'] = $ticket->sid;
            //$orderBase['parent_other_id'] = 0; //合作网站父订单号--现用于百度直达号
            //$orderBase['parent_order_id'] = 0; //着想网站父订单号--现用于百度直达号
            //$orderBase['audit_id'] = 0; //合作网站退票审核id,或串码,或银行交易流水号-现用于百度直达号,银科环企网站串码,美团接口银行交易流水号,红海滩接口验证码
            //$orderBase['is_delete'] = 1;
            $orderBase['pay_id'] = $payRecordId;
            $orderBase['api_id'] = $ticket->o_api_id;
            $orderBase['is_edit'] = $ticket->is_edit;
            $orderBase['is_refund'] = $ticket->is_refund;
            $orderBase['is_partial_refund'] = $ticket->is_partial_refund;
            $orderBase['refund_day'] = $ticket->refund_day;
            $orderBase['refund_time'] = $ticket->refund_time;
            $orderBase['calculate_method'] = 3;//1:分润 2:议价 3:扫码购
            $orderBase['order_source'] = 2; //1:PC端；2:手机端

            $orderId = $this->order_base->insertOrderBase($orderBase);
            //$update = $this->goods_base->setTicketStock(array('goods_id'=>$goodsId, 'limit_number'=>-$buyNum)); //下单时减去库存
            
            //景区订单分润表
            $scenicProfit[$orderId] = $this->createProfit($resutlScenery->uid, $ticket->goods_id, $ticketPayTotal);
    
            $level = $level|$ticket->cat_id;
            $cat_ids[] = $ticket->cat_id;
            $goods_ids[] = $ticket->goods_id;
            $goods_nums[] = $buyNum;
            $order_ids[] = $orderId;
            // $orderBouns += bcmul($ticket->off_bonus, $buyNum, 2);
            $orderPayTotal += $ticketPayTotal; //订单实际应该支付的总价
            $payRecordBody .= $ticket->goods_name.'['.$buyNum.'张]';
        }

        $profitBatch = $this->order_profit->insertBatch($scenicProfit);

        /*-------订单修改--------*/
        // if ($buyBouns && $buyBouns<=$orderBouns) { //是否选择使用金币
        //     $orderBouns = $buyBouns;
        // }
        $payRecord['pay_id']     = $payRecordId;
        $payRecord['uid']        = $this->uid;
        $payRecord['level']      = $level;
        $payRecord['cat_ids']    = serialize($cat_ids);
        $payRecord['goods_ids']  = serialize($goods_ids);
        $payRecord['goods_nums'] = serialize($goods_nums);
        $payRecord['order_ids']  = serialize($order_ids);
        $payRecord['order_bouns']= 0;
        $payRecord['amount']     = $orderPayTotal;
        $payRecord['body']       = $payRecordBody;
        $updatePay = $this->pay_record->updatePayRecord($payRecord);

        if ($this->db->trans_status() === FALSE || !$payRecordId || !$updatePay) {
            $this->db->trans_rollback();
            $this->jsonMessage('订单生成失败');
        }
        $this->db->trans_commit();

        $this->jsonMessage('', site_url('scenic/payment/payOrderScenic/'.$payRecordId));
    }

    /**
     * 验证购买门票的信息
     * @param unknown $ticket
     * @param unknown $buyticket
     */
    public function validateBuyTicket($ticket, $buyNum)
    {
        $goodsId = $ticket->goods_id;
        $buyDate = date('Y-m-d'); //当前购买日期

        //销售时间
        if ($ticket->sell_start_time != 0 && $buyDate < date('Y-m-d', $ticket->sell_start_time)) {
            return $ticket->goods_name.'不在销售时间内，请选择其它时间段';
        }
        if ($ticket->sell_end_time != 0 && (strtotime($buyDate) > $ticket->sell_end_time || time() > $ticket->sell_end_time)) {
            return $ticket->goods_name.'超出可售时间，请选择其它时间段';
        }
        
        //验证库存
        if ($buyNum > $ticket->limit_number) {
            return $ticket->goods_name.'当前购买张数大于实际库存'.$ticket->limit_number.'张';
        }

        //验证限制用户购买数量
        if ($buyNum < $ticket->min_number) {
            return $ticket->goods_name.'购买张数必须要大于等于最小购买张数（'.$ticket->min_number.'）张';
        }

        //指定购买者
        if (!empty($ticket->buyers) && !in_array($this->uid, explode('|', $ticket->buyers))) {
            return $ticket->goods_name.'只有指定的用户才可以购买';
        }

        //指定不可购买者
        if (!empty($ticket->unbuyers) && in_array($this->uid, explode('|', $ticket->unbuyers))) {
            return '抱歉，您不能购买'.$ticket->goods_name.'门票';
        }

        //验证身份证的有效性
        $visitorSfz = $this->input->post('visitor_sfz');
        if (!empty($visitorSfz)) {
            validateSfz($visitorSfz);
        }

        //除了周末时间，均可购买
        if ($ticket->bit_opt&4096) {
            $weekDay = date('w', strtotime($buyDate));
            if (!in_array($weekDay, array(1,2,3,4,5))) {
                return '抱歉，'.$ticket->goods_name.'属于日常票，除了周末时间均可购买';
            }
        }

        //只能周末时间购买
        if ($ticket->bit_opt&8192) {
            $weekDay = date('w', strtotime($buyDate));
            if (in_array($weekDay, array(1,2,3,4,5))) {
                return '抱歉，'.$ticket->goods_name.'属于周末票，请选择周末时间购买';
            }
        }

        //限止一个身份证能购买一种类型门票的最大张数,以预订频次限制为标准
        if ($ticket->limit_sfz_number > 0) {
            $buy_number = 0; //已购买数量
            $result = $this->order_base->findByParams(array('select'=>'number,ordertime', 'sfz'=>$visitorSfz, 'goods_id'=>$goodsId, 'bit_pay'=>0, 'goods_num'=>0));
            if ($result->num_rows() > 0) {
                $order_result = $result->result();//获得多条记录
                switch ($ticket->sfz_booking_limit) {
                    case 1: //1天:可以多次购买,但1天之内只能购买不大于最大数的门票数
                        foreach ($order_result as $value) {
                            $order_time_date = date('Y-m-d', $value->ordertime);//之前下单日期
                            $current_order_date = date('Y-m-d');//当前下单日期
                            //如果之前下单日期等于当前下单日期,已购买订单数量就等于之前下单数量的总和
                            if ($order_time_date == $current_order_date) {
                                $buy_number += $value->number;
                            }
                        }
                        break;
                    case 2: //1周:可以多次购买,但1周之内只能购买不大于最大数的门票数
                        foreach ($order_result as $value) {
                            $order_time_week = date('W', $value->ordertime);//根据之前下单时间戳计算是一年中的第几周
                            $current_order_week = date('W', time());//根据当前下单时间戳计算是一年中的第几周
                            //如果之前下单周数等于当前下单周数,已购买订单数量就等于之前下单数量的总和
                            if ($order_time_week == $current_order_week) {
                                $buy_number += $value->number;
                            }
                        }
                        break;
                    case 3: //1月:可以多次购买,但1月之内只能购买不大于最大数的门票数
                        foreach ($order_result as $value) {
                            $order_time_month = date('Y-m', $value->ordertime);//根据之前下单月份
                            $current_order_month = date('Y-m');//根据当前下单月份
                            //如果之前下单月份等于当前下单月份,已购买订单数量就等于之前下单数量的总和
                            if ($order_time_month == $current_order_month) {
                                $buy_number += $value->number;
                            }
                        }
                        break;
                    case 4: //1年:可以多次购买,但1年之内只能购买不大于最大数的门票数
                        foreach ($order_result as $value) {
                            $order_time_year = date('Y', $value->ordertime);//根据之前下单年份
                            $current_order_year = date('Y');//根据当前下单年份
                            //如果之前下单年份等于当前下单年份,已购买订单数量就等于之前下单数量的总和
                            if ($order_time_year == $current_order_year) {
                                $buy_number += $value->number;
                            }
                        }
                        break;
                    case 0: //无限制:可以多次购买,但一次购买的数量不能超过最大数
                    default:
                        break;
                }
            }
            //已购买的票数+当前购买票数大于限制购买的最大票数
            if (($buy_number+$buyNum) > $ticket->limit_sfz_number) {
                return $ticket->goods_name.'当前身份证超出限制购买张数（'.($buy_number+$buyNum-$ticket->limit_sfz_number).'）张';
            }
        }

        //限止指定地区不能购买
        if (!empty($ticket->limit_area)) {
            $limitArea = explode('|', $ticket->limit_area);
            $flag = false;
            foreach($limitArea as $shortArea) {
                if (!empty($shortArea)) {
                    $shortSfz = mb_substr($visitorSfz, 0, strlen($shortArea));
                    if ($shortSfz == $shortArea) {
                        $flag = true;
                    }
                }
            }
            if ($flag) {
                return '抱歉，由于区域限制，您的身份证不能购买'.$ticket->goods_name.'门票';
            }
        }

        //限止指定地区可以购买
        if (!empty($ticket->access_area)) {
            $accessArea = explode('|', $ticket->access_area);
            $flag = true;
            foreach ($accessArea as $shortAccess) {
                if (!empty($shortAccess)) {
                    $short_sfz = mb_substr($visitorSfz, 0, strlen($shortAccess));
                    if ($short_sfz == $shortAccess) {
                        $flag = false;
                    }
                }
            }
    
            if ($flag) {
                return '抱歉，由于区域限制，您的身份证不能购买'.$ticket->goods_name.'门票';
            }
        }
    }

    /**
     * 生成订单pay_record表数据
     */
    public function createPayRecode()
    {
        $payRecord = array(); //订单支付
        $payRecord['level'] = 0;
        $payRecord['cat_ids'] = 0;
        $payRecord['goods_ids'] = 0;
        $payRecord['goods_nums'] = 0;
        $payRecord['order_ids'] = 0;
        $payRecord['uid'] = $this->uid;
        $payRecord['phone'] = $this->input->post('mobile_phone');
        $payRecord['pay_method'] = 0;
        $payRecord['amount'] = 0; //需支付总金额
        $payRecord['subject'] = '交易款';
        $payRecord['body'] = '';
        $payRecord['info'] = '0';
        $payRecord['bit_state'] = 0;
        $payRecord['pay_time'] = 0;
    
        return $this->pay_record->insertPayRecord($payRecord);
    }

    /**
     * ajax发送短信
     */
    public function ajaxSendSms()
    {
        $phone = $this->input->post('mobilePhone');
        if (!validateMobilePhone($phone)) {
            $this->jsonMessage('手机号码格式有误');
        }

        $code = mt_rand(100000, 999999);
        $result = $this->getpwd_phone->findByPhone($phone);
        if ( $result->num_rows() > 0 ) {
            $status = $this->getpwd_phone->updateGetpwdPhone(array('mobile_phone'=>$phone, 'code'=>$code));
        } else {
            $status = $this->getpwd_phone->insertGetpwdPhone(array('mobile_phone'=>$phone, 'code'=>$code));
        }
        $this->sendToSms($phone, '验证码:'.$code.'，有效期为10分钟。千万不要告诉他人！');
        if ($status) {
            $this->jsonMessage('');
        } else {
            $this->jsonMessage('网络繁忙，请稍后重新获取验证码');
        }
    }

    /**
     * 创建分润  只分给 供应商
     */
    private function createProfit($uid, $goodsId, $amount)
    {
        $goodsProfit = $this->goods_map_profit->findByParams(array('goods_id' => $goodsId, 'bit_trade' => 1));
        $payees = array();

        $flag = TRUE;
        if ($goodsProfit->num_rows() > 0) {
            $profitAmount = $amount;
            //通过兴业银行结算  不需要分钱给景区账户
            if (in_array($uid, array(2005375,3552545, 100254, 3533563,2009566))) {
                $profitAmount = 0;
            }
            foreach ($goodsProfit->result() as $key => $value) {

                if ($value->uid == $uid) {
                    $flag = FALSE;
                }
                $payees[] = array(
                    'us'        => UTID_BEIZHU,
                    'ut'        => $value->uid,
                    'as'        => ACCOUNT_TYPE_SETTLEMENT, //1-可提现；2-冻结；4-金币；8：积份；16：月结
                    'at'        => ACCOUNT_TYPE_CARRY,
                    'amount'    => ($value->uid == $uid) ? $profitAmount : 0,
                    'step'      => 2, //1交易被创建 2交易被支付 3交易被消费 4交易被取消 5交易完成
                    'bit_trade' => 1
                );
            }
        }

        // 门票分润表里 不存在景区供应商
        if ($flag) {
            $this->jsonMessage('门票信息有误');
        }

        //付款人
        $payees[] = array(
            'us'        => $this->uid,
            'ut'        => UTID_BEIZHU,
            'as'        => ACCOUNT_TYPE_CARRY, //1-可提现；2-冻结；4-金币；8：积份；16：月结
            'at'        => ACCOUNT_TYPE_SETTLEMENT,
            'amount'    => $amount,
            'step'      => 2, //1交易被创建 2交易被支付 3交易被消费 4交易被取消 5交易完成
            'bit_trade' => UTID_ACTUAL
        );

        return $payees;
    }
}
